package com.farm.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.farm.dto.CartGroupDTO;
import com.farm.entity.CartItem;
import com.farm.entity.User;
import com.farm.service.CartService;

@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    @GetMapping("/cart")
    public String viewCart(@AuthenticationPrincipal User user, Model model) {
        List<CartItem> cartItems = cartService.getCartItems(user);
        
        // 按农户分组
        Map<User, List<CartItem>> itemsByFarmer = cartItems.stream()
                .collect(Collectors.groupingBy(item -> item.getProduct().getFarmer()));
        
        // 转换为 DTO
        List<CartGroupDTO> groupedItems = itemsByFarmer.entrySet().stream()
                .map(entry -> new CartGroupDTO(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
        
        // 计算总金额
        BigDecimal total = groupedItems.stream()
                .map(CartGroupDTO::getSubtotal)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        model.addAttribute("cartItems", cartItems);
        model.addAttribute("groupedItems", groupedItems);
        model.addAttribute("total", total);
        model.addAttribute("currentUser", user);
        return "cart";
    }

    @PostMapping("/cart/add")
    @ResponseBody
    public String addToCart(
            @AuthenticationPrincipal User user,
            @RequestParam Long productId,
            @RequestParam Integer quantity) {
        try {
            cartService.addToCart(user, productId, quantity);
            return "success";
        } catch (Exception e) {
            return "error: " + e.getMessage();
        }
    }

    @PostMapping("/cart/update/{cartItemId}")
    @ResponseBody
    public String updateCartItem(
            @AuthenticationPrincipal User user,
            @PathVariable Long cartItemId,
            @RequestParam Integer quantity) {
        try {
            cartService.updateCartItemQuantity(user, cartItemId, quantity);
            return "success";
        } catch (Exception e) {
            return "error: " + e.getMessage();
        }
    }

    @PostMapping("/cart/remove/{cartItemId}")
    @ResponseBody
    public String removeFromCart(
            @AuthenticationPrincipal User user,
            @PathVariable Long cartItemId) {
        try {
            cartService.removeCartItem(user, cartItemId);
            return "success";
        } catch (Exception e) {
            return "error: " + e.getMessage();
        }
    }

    @PostMapping("/cart/clear")
    public String clearCart(
            @AuthenticationPrincipal User user,
            RedirectAttributes redirectAttributes) {
        try {
            cartService.clearCart(user);
            redirectAttributes.addFlashAttribute("success", "购物车已清空");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "清空购物车失败：" + e.getMessage());
        }
        return "redirect:/cart";
    }
} 